package com.xiyu.service.repository.restaurant.dish;

import com.xiyu.service.model.restaurant.dish.*;
import com.xiyu.service.vo.restaurant.dish.DishQueryInput;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.Page;
import org.springframework.util.StringUtils;

import java.util.Optional;

public interface RestaurantDishRepository extends JRepository<RestaurantDish, Long> {
    RestaurantDishTable restaurantDishTable = RestaurantDishTable.$;

    default Page<RestaurantDish> pageQuery(DishQueryInput inputVO){
        return sql().createQuery(restaurantDishTable)
                .whereIf(StringUtils.hasText(inputVO.getName()), () -> restaurantDishTable.name().like(inputVO.getName()))
                .whereIf(inputVO.getTypeId() != null, restaurantDishTable.typeId().eq(inputVO.getTypeId()))
                .whereIf(inputVO.getCreateTime() != null, ()-> restaurantDishTable.createTime().between(inputVO.getCreateTime()[0], inputVO.getCreateTime()[1]))
                .orderBy(restaurantDishTable.id().desc())
                .select(restaurantDishTable.fetch(RestaurantDishFetcher.$.allTableFields().type(RestaurantDishTypeFetcher.$.allTableFields())))
                .fetchPage(inputVO.getPageNo() - 1, inputVO.getPageSize());
    }

    default Optional<RestaurantDish> findDetailById(Long id){
        return sql().createQuery(restaurantDishTable)
                .where(restaurantDishTable.id().eq(id))
                .select(restaurantDishTable.fetch(RestaurantDishFetcher.$.allTableFields().materials(RestaurantDishMaterialFetcher.$.allTableFields())))
                .fetchOptional();
    }

    Optional<RestaurantDish> findFirstByName(String name);

    Optional<RestaurantDish> findFirstByNameAndIdNot(String name, Long id);
}